package br.quest.gps;

import br.quest.Config;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class GPS {

    private Activity manager;
    private static GPS instance;
    private GPSListener listener;
    private LocationManager locManager;

    private GPS() {
    }

    /**
     * Returns an instance of GPS
     * 
     * @return The working instance of this manager.
     * @throws An Exception if it's not yet configured.
     */
    public static GPS getInstance() {
        if (instance == null)
            throw new NullPointerException("GPS not configured yet. Call configure() first.");
        return instance;
    }

    /**
     * Creates a single intance of PreferenceManager, passing a Context object. This method MUST be called before get(),
     * or else you'll get an Exception. This method must be called only once, preferably on the startup of your app.
     * 
     * @param holder The activity which will manage the GPS. This should be the app main activity
     */
    public static void configure(Activity manager) {
        instance = new GPS();
        instance.manager = manager;
        instance.locManager = (LocationManager) instance.manager.getSystemService(Context.LOCATION_SERVICE);
    }

    /**
     * Reads the last known position for the GPS. Note that this location could be out-of-date, for example if the
     * device was turned off and moved to another location.
     * 
     * @return The Location indicating the position.
     */
    public Location readLastPosition() {
        return locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }

    /**
     * Returns the current enabled/disabled status of the GPS. If the user has enabled GPS in the Settings menu, true is
     * returned otherwise false is returned
     */
    public boolean isGpsWorking() {
        return locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * Start reading GPS data. The default minDistance between points is 25m.
     * 
     * @param pointListener The listener on which all the Waypoints found will be passed to. Use this to decide what to
     *        do with the points.
     */
    public void startReading(WaypointListener pointListener) {
        listener = GPSListener.getInstance();
        listener.setWaypointListener(pointListener);
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Config.getGpsMinTime(),
                Config.getGpsMinDistance(), listener);
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, Config.getGpsMinTime(),
                Config.getGpsMinDistance(), listener);
    }

    /**
     * Stops reading GPS data.
     */
    public void stopReading() {
        locManager.removeUpdates(listener);
    }
}
